@echo off
:: 功能：在服务器上部署学生月考成绩管理系统
:: 说明：此脚本用于在服务器环境中部署应用

set IMAGE_NAME=appexecel2student
set CONTAINER_NAME=appexecel2student
set TEMP_IMAGE_NAME=%IMAGE_NAME%-temp

echo ========================================
echo   服务器部署 - 学生月考成绩管理系统
echo ========================================
echo.

:: 检查 MySQL 容器是否存在
echo [检查] 验证 MySQL 容器...
docker ps -a --filter "name=mysql" --format "{{.Names}}" | findstr /C:"mysql" >nul
if %errorlevel% neq 0 (
    echo [警告] 未找到名为 'mysql' 的容器
    echo [提示] 请确保 MySQL 容器正在运行，或修改 backend/.env.docker 中的 DB_HOST
    echo.
    set /p CONTINUE="是否继续部署？(Y/N): "
    if /i not "%CONTINUE%"=="Y" (
        echo 部署已取消
        pause
        exit /b 1
    )
)

:: 检查 mynet 网络是否存在
echo [检查] 验证 Docker 网络 mynet...
docker network ls --filter "name=mynet" --format "{{.Name}}" | findstr /C:"mynet" >nul
if %errorlevel% neq 0 (
    echo [创建] 创建 Docker 网络 mynet...
    docker network create mynet
    if %errorlevel% neq 0 (
        echo [错误] 创建网络失败
        pause
        exit /b 1
    )
)

echo.
echo Step 1: Building new temporary image: %TEMP_IMAGE_NAME%
docker build -t %TEMP_IMAGE_NAME% .
if %errorlevel% neq 0 (
    echo [错误] Docker 镜像构建失败！
    pause
    exit /b 1
)

echo.
echo Step 2: Stopping and removing existing container: %CONTAINER_NAME%
docker stop %CONTAINER_NAME% >nul 2>&1
docker rm %CONTAINER_NAME% >nul 2>&1

echo.
echo Step 3: Removing old image: %IMAGE_NAME%
docker rmi %IMAGE_NAME% >nul 2>&1

echo.
echo Step 4: Tagging temporary image to final name: %IMAGE_NAME%
docker tag %TEMP_IMAGE_NAME% %IMAGE_NAME%
docker rmi %TEMP_IMAGE_NAME%

echo.
echo Step 5: Running new container: %CONTAINER_NAME%
docker run -d ^
  --name %CONTAINER_NAME% ^
  -p 7661:3000 ^
  -p 7662:80 ^
  --network=mynet ^
  --restart unless-stopped ^
  %IMAGE_NAME%

if %errorlevel% neq 0 (
    echo [错误] 容器启动失败！
    pause
    exit /b 1
)

echo.
echo ========================================
echo   部署完成！
echo ========================================
echo.
echo 访问地址:
echo   学生查询: http://YOUR_SERVER_IP:7662
echo   管理后台: http://YOUR_SERVER_IP:7662/admin
echo   后端 API: http://YOUR_SERVER_IP:7661
echo.
echo 容器状态:
docker ps --filter "name=%CONTAINER_NAME%"
echo.
echo [提示] 请将 YOUR_SERVER_IP 替换为实际的服务器 IP 地址
echo.

:: 测试数据库连接
echo [测试] 检查数据库连接...
timeout /t 3 /nobreak >nul
docker logs %CONTAINER_NAME% --tail 10 | findstr /C:"数据库连接成功" >nul
if %errorlevel% equ 0 (
    echo [成功] 数据库连接正常
) else (
    echo [警告] 数据库连接可能有问题，请检查日志:
    echo         docker logs %CONTAINER_NAME%
)

echo.
pause
